package jmine.tec.rpc.common.serialization.json;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import jmine.tec.json.JSON;
import jmine.tec.json.JSONArray;
import jmine.tec.json.JSONObject;
import jmine.tec.json.JSONString;
import jmine.tec.utils.collection.IdentityHashSet;

/**
 * Conversor de JSON para Java e vice-versa
 * 
 * @author lundberg
 */
public class JSONSetConverter extends AbstractJSONObjectConverter<Set<Object>> implements JSONConverterStrategy {

    private static final String ELEMENTS = "elements";

    /**
     * {@inheritDoc}
     */
    public boolean matchesJava(Object object) {
        return object instanceof Set;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected JSON objectType() {
        return new JSONString("set");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Set<Object> instantiate(JSONConversionContext context, JSON json) {
        return new IdentityHashSet<Object>();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillObject(JSONConversionContext context, JSON json, Set<Object> object) {
        JSONArray jsonArray = (JSONArray) json.getProperty(ELEMENTS);
        for (int i = 0; i < jsonArray.getSize(); i++) {
            object.add(context.toJava(jsonArray.getProperty(i)));
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillJSON(JSONConversionContext context, Object object, JSONObject json) {
        Set<?> list = (Set<?>) object;
        List<JSON> elements = new ArrayList<JSON>(list.size());
        for (Object e : list) {
            elements.add(context.toJSON(e));
        }
        json.setProperty(ELEMENTS, new JSONArray(elements));
    }
}
